using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

using GURUCORE.Framework.Core;

namespace GURUCORE.Framework.Business
{
	public class ServiceLocator
	{
		/*public static T Locate<T>(Type p_tImplementType, Type p_tProxyType, bool p_bRemote, string p_sURL) where T: class
		{
			Type tType = typeof(T);

			if (p_bRemote) 
			{
				//return instance of proxy
				return (T)Activator.CreateInstance(p_tProxyType, new object[] {p_sURL});
			}
			else
			{
				//return instance from service loader
				return (T)ServiceClassLoader.CreateInstance(p_tImplementType);
			}
		}

		public static Interface Locate<Interface,ImplementType,ProxyType>(bool p_bRemote, string p_sURL) where Interface : class where ImplementType : class where ProxyType : class
		{
			if (p_bRemote) 
			{
				//return instance of proxy
				return (Interface)Activator.CreateInstance(typeof(ProxyType), new object[] {p_sURL});
			}
			else
			{
				//return instance from service loader
				return (Interface)ServiceClassLoader.CreateInstance(typeof(ImplementType));
			}
		}*/

		public static Interface Locate<Interface, DirectImplementation>()
		{
			//retrieve service factory
			string sInterface = typeof(Interface).FullName;
			ServiceFactory oSvcFactory = (ServiceFactory)GApplication.GetInstance().GetSharedObject(ServiceFactory.GLOBAL_CACHE_KEY);

            object oImplementationInstance = null == oSvcFactory ? null : oSvcFactory.GetImplementation(sInterface);
            if (oImplementationInstance != null)
            {
                try
                {
                    return (Interface)oImplementationInstance;
                }
                catch (Exception ex)
                {
                    throw new FrameworkException("Invalid implementation class for business service interface. Can't cast [" + oImplementationInstance.ToString() + "] to [" + typeof(Interface).FullName + "]", ex);
                }
            }
            else
            {
                return (Interface)ServiceClassLoader.CreateInstance(typeof(DirectImplementation));
            }
            
		}

	}
}
